package com.dmcliver.timetracker.persistence;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;

import com.dmcliver.timetracker.entity.Person;
import com.dmcliver.timetracker.entity.Timeentry;

@AutoCreate
@Name("personDAO")
public class PersonDAOImpl implements PersonDAO {
	
	@In EntityManager entityManager;
	
	public List<Person> findAll(){
		
		CriteriaBuilder criteria = entityManager.getCriteriaBuilder();
		CriteriaQuery<Person> query = criteria.createQuery(Person.class);
		
		Root<Person> p = query.from(Person.class);
		query.select(p);
		
		return entityManager.createQuery(query).getResultList();
	}
	
	public boolean exists(String userName) {

		CriteriaBuilder criteria = entityManager.getCriteriaBuilder();
		CriteriaQuery<Long> query = criteria.createQuery(Long.class);
		
		Root<Person> p = query.from(Person.class);
		query.select(criteria.count(p)).where(criteria.equal(p.get("username"), userName));
		
		return entityManager.createQuery(query).getSingleResult() > 0;
	}
	
	public boolean exists(String userName, String password){
		
		CriteriaBuilder criteria = entityManager.getCriteriaBuilder();
		CriteriaQuery<Long> query = criteria.createQuery(Long.class);
		
		Root<Person> p = query.from(Person.class);
		query.select(criteria.count(p));
		query.where(criteria.and(
			criteria.equal(p.get("username"), userName),
			criteria.equal(p.get("userpassword"), password)
		));
		
		Long singleResult = entityManager.createQuery(query).getSingleResult();
		return singleResult > 0;
	}

	public List<Person> getAllPeopleWithFirstnameToday(String firstName){
		
		CriteriaBuilder criteria = entityManager.getCriteriaBuilder();
		CriteriaQuery<Person> query = criteria.createQuery(Person.class);
		
		Root<Person> p = query.from(Person.class);	
		query.select(p);
		Join<Person, Timeentry> te = p.join("timeentries", JoinType.LEFT);
		query.where(criteria.and(
			criteria.lessThanOrEqualTo(te.<Date>get("startdatetime"), new Date()),
			criteria.equal(p.<String>get("firstname"), firstName)
		));
		
		List<Person> resultList = entityManager.createQuery(query).getResultList();
		return resultList;
	}

	public void persist(Person person) {

		entityManager.persist(person);
		entityManager.flush();
	}
}
